﻿@model JewererBasic.ORDER_TREE

<h2>Order Tree</h2>
@using (Html.BeginForm("CreateOrder", "TreeOrder", FormMethod.Post, new { id = "formBagControl" }))
{
    <fieldset>
    <input type="button" id="add" value="Add Tree" />
    <input type="submit" value="Finish" id="btnFinish"  style="display: none" />
    @Html.HiddenFor(m=>m.Order_Tree_Id, new {@id="txtTreeId", @name="Order_Tree_Id"})
    <div id="orderDetail">
    </div>
    <!--Show current list-->
    </fieldset>
}
@section Scripts{
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="@Url.Content("~/Scripts/json2.min.js")" type="text/javascript"></script>
    <script type="text/javascript">

        // add new Order_Tree_Detail
        var index = 0;
        $('#add').click(function () {
            addComponent(index, "", "", "");
            $("#btnFinish").show();
            ++index;
        });
        function addComponent(index) {

            // using for dropdownlist of workers
            var values;
            var texts;

            $.ajax({
                url: '/ComponentOrder/GetWorkerId',
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                async: false,
                success: function (data) {
                    var tmpStr = "";
                    tmpStr = data.values;
                    values = tmpStr.split(";");
                    tmpStr = data.texts;
                    texts = tmpStr.split(";");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                }
            });

            var dropdownlist = '<select id="ddlWorkerId" class="WorkerId" required>';
            for (var i = 0; i < values.length - 1; i++) {
                dropdownlist += '<option value="' + values[i] + '">' + texts[i] + '</option>';
            }
            dropdownlist += '</select>';

            $('#orderDetail').append('<p class="pComponentTag">' +
                                 '<strong class="myStrong">ComponentId</strong><input type="text" class="ItemComponent" style = "width:150px;" id="ItemComponent' + index + '" placeholder="Component Id" required>' +
                                 '<strong class="myStrong">Export Weight</strong><input type="text" class="WeightNumber" id="WeightComponent' + index + '" placeholder="Export Weight" style = "width:100px;" required>' +
                                 //'<strong class="myStrong">Worker Id</strong><input type="text" class="WorkerId" id="WorkerId' + index + '"  placeholder="Worker Id"  style = "width:100px;" required>' +
                                 dropdownlist +
                                 '<strong class="myStrong">List Bag</strong><textarea rows="6" cols="20" class="lstBagId" id="lstBagId' + index + '" placeholder="List Bag Codes" style="vertical-align:middle" required/>' +
                                 '<a href="#" id="removeComponent" class="myA">Remove </a> </p>');
            var component = $("#ItemComponent" + index);
            $(component).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/NewProduct/Components',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(component).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });
            // remove additional elements
            $(document).on("click", "#removeComponent ", function () {
                $(this).parents('p').remove();
                var length = $("#orderDetail").children().length;
                if (length == 0) {
                    $("#btnFinish").hide();
                }
                return false;
            });
        }

        // submit
        function ORDER_TREE_DETAIL(Component_Id, ExportWeight, WorkerId, ListBag) {
            var self = this;
            self.Component_Id = Component_Id;
            self.ExportWeight = ExportWeight;
            self.WorkerId = WorkerId;
            self.ListBag = ListBag;
        }
        $(document).ready(function () {
            $("form").submit(function (evt) {
                // collect all information
                var flag = false;
                var models = new Array();
                $('.pComponentTag').each(function () {
                    if (!flag) {
                        var Component_Id = $(this).children('.ItemComponent').val();
                        var ExportWeight = $(this).children('.WeightNumber').val();
                        var WorkerId = $(this).children('.WorkerId').val();
                        var ListBag = $(this).children('.lstBagId').val();;

                        if (!Component_Id || !ExportWeight || !WorkerId || !ListBag) {
                            alert("Missing information");
                            flag = true;
                        } else {
                            var weight = parseFloat(ExportWeight);
                            if(weight > 0){
                                //  check component id
                                $.ajax({
                                    type: "GET",
                                    contentType: "application/json; charset=utf-8",
                                    url: '/TreeOrder/IsComponentExisted',
                                    data: { "id": Component_Id },
                                    dataType: "json",
                                    async: false,
                                    beforeSend: function () {//alert();
                                    },
                                    success: function (data) {
                                        if (data.result == true) {
                                            var model = new ORDER_TREE_DETAIL(Component_Id, ExportWeight, WorkerId, ListBag);
                                            models.push(model);
                                        } else {
                                            alert(Component_Id + "is not existed!");
                                            flag=true;
                                        }
                                    },
                                });

                                //var model = new ORDER_TREE_DETAIL(Component_Id, ExportWeight, WorkerId, ListBag);
                                //models.push(model);
                            }else{
                                alert("Export Weight is invalid!");
                                flag = true;
                            }                           
                        }
                    }
                });

                // post 
                //var id = $('#txtTreeId').val();
                if (!flag && models.length > 0) {
                    postData = { models: models};
                    $.ajax({
                        url: '/TreeOrder/CreateOrderSubmit',
                        type: 'POST',
                        dataType: 'json',
                        data: JSON.stringify(postData),
                        contentType: 'application/json; charset=utf-8',
                        async: false,
                        success: function (data) {
                            if (!data.success) {
                                alert("Error in tree order controller");
                                evt.preventDefault();
                            }else{
                                $('#txtTreeId').val(data.id);
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert("Error in Tree Order View");
                            evt.preventDefault();
                        }
                    });
                }
                else {
                    var error1 = "";
                    var error2 = "";
                    if (flag) error1 = "Data is invalid";
                    if (data.length < 1) error2 = "No Tree!";
                    alert(error2+"\r\n"+error1);
                    evt.preventDefault();
                }
            });
        });
    </script>
}
